//
//  WebServices.m
//  GKBHouse
//
//  Created by  on 12-7-7.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "WebServices.h"
#import "SystemSettting.h"
#import "OperationTip.h"
#import "LoginController1.h"

WebServices *_webService = nil;
static BOOL showConnectting = YES;

@implementation MyFormDataRequest
@synthesize endTarget, endAction;
@synthesize errorTip;
@synthesize index;


- (id)initWithURL:(NSURL *)newURL
{
    self = [super initWithURL:newURL];
    return self;
}
- (void)setEndTarget:(id)target endAction:(SEL)action errorTip:(NSString *)_errorTip
{
    self.endTarget = target;
    self.endAction = action;
    self.errorTip = _errorTip;
}
- (void)dealloc
{
    self.endTarget = nil;
    [super dealloc];
}
@end
@implementation WebServices
@synthesize requestTarget, requestAction;
@synthesize errorTip;
@synthesize queueDic;
@synthesize queueIndex;
@synthesize requestDic;

+ (void)setShowConnectting:(BOOL)show
{
    showConnectting = show;
}
+ (BOOL)showConnectting
{
    return showConnectting;
}
+ (NSURL *)url
{
    NSString *url = [SystemSettting systemUrl];
    return [NSURL URLWithString:url];
//    return [NSURL URLWithString:@"http://www.gkbhome.com:10000/gkbws/services/AIClientWebservice?wsdl"];
}
+ (WebServices *)webService
{
    if(!_webService)
    {
        _webService = [[WebServices alloc]init];
        _webService.queueIndex = 0;
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        _webService.queueDic = dic;
        NSMutableDictionary *reqDic = [NSMutableDictionary dictionary];
        _webService.requestDic = reqDic;
      //  [_webService initNetWorkQueue];
    }
    _webService.queueIndex++;
    if (_webService.queueIndex >1000) {
        _webService.queueIndex = 0;
    }
    //[_webService setCurrentQueue];
    return _webService;
}
- (void)dealloc
{
    self.requestDic = nil;
    self.queueDic = nil;
    [self cancelService];
    [networkQueue release];
    
    [super dealloc];
}
- (void)cancelService
{
    self.requestTarget = nil;
    self.requestAction = nil;
    [networkQueue reset];
}
- (void)initNetWorkQueue
{
    if (!networkQueue) {
		networkQueue = [[ASINetworkQueue alloc] init];	
	}
    
	[networkQueue reset];
    
	[networkQueue setRequestDidFinishSelector:@selector(requestDone:)];
	[networkQueue setRequestDidFailSelector:@selector(requestWrong:)];
    
	[networkQueue setDelegate:self];
    [networkQueue go];
}
- (void)setCurrentQueue
{
    ASINetworkQueue *queue = [[[ASINetworkQueue alloc]init]autorelease];
    [queue reset];    
	[queue setRequestDidFinishSelector:@selector(requestDone:)];
	[queue setRequestDidFailSelector:@selector(requestWrong:)];
	[queue setDelegate:self];
    [queue go];
    
    NSString *index = [NSString stringWithFormat:@"%d", queueIndex];
    [self.queueDic setValue:queue forKey:index];
    networkQueue = queue;
    NSLog(@"queueIndex:%d, %@", self.queueIndex, self.queueDic);
}
- (void)removeQueueIndex:(NSInteger)index
{
    NSLog(@"queueIndex:%d, %@", self.queueIndex, self.queueDic);
    NSString *indexStr = [NSString stringWithFormat:@"%d", index];
    [self.queueDic removeObjectForKey:indexStr];
}
- (void)saveRequestDic:(MyFormDataRequest *)request
{
    NSString *index = [NSString stringWithFormat:@"%d", request.index];
    [self.requestDic setValue:request forKey:index];
     NSLog(@"saveIndex:%d, %@", request.index, self.requestDic);
}
- (void)removeRequestDicIndex:(NSInteger)index
{
     NSLog(@"removeIndex:%d, %@", index, self.requestDic);
    NSString *indexStr = [NSString stringWithFormat:@"%d", index];
    [self.requestDic removeObjectForKey:indexStr];
}
- (void)startOperation:(ASIFormDataRequest *)request
{
    if ([WebServices showConnectting]) {
        [self addConnectTip];
    }
    NSLog(@"operationCount:%d", [networkQueue operationCount]);
    [networkQueue addOperation:request];
    

}
- (void)startRequest:(MyFormDataRequest *)request
{
    if ([WebServices showConnectting]) {
        [self addConnectTip];
    }
    [request startAsynchronous];
}
- (void)requestDone:(MyFormDataRequest*)request
{
    [self removeConnectTip];
    [self removeQueueIndex:request.index];
    
    NSString *responseString;
    responseString = [request responseString];
//    NSLog(@"requestDone:%@",responseString);
    
    NSError *error;
    
    GDataXMLDocument *Document = [[GDataXMLDocument alloc]initWithXMLString:responseString options:0 error:&error];
    if (Document == nil) {
        NSString *errorType = [OperationTip errorType:ErrorTypeServerDataFail];
        [iToast showTip:errorType gravity:iToastGravityBottom];
        return;
    }
    GDataXMLElement *rootNode = [Document rootElement];    
    
    NSString *loginReturn = [xmlMore GetNodeString:rootNode node:@"/soapenv:Envelope"];      
    SBJsonParser *parser=[[SBJsonParser alloc] init];     
    NSArray *arrayData=[parser objectWithString:loginReturn];
    
    NSDictionary *jsonData=[arrayData objectAtIndex:0];
    if (request.endTarget && request.endAction) {
        NSLog(@"net end");        
        
        if (![WebServices showConnectting]) {
            NSNumber *result = [jsonData objectForKey:@"result"];
            if (result.integerValue == 2) {//session超时
                GKBMainController *mainCtr = [GKBMainController mainCtr];
                if (mainCtr) {
                    [LoginController1 setAutoLogin:NO];
                    [mainCtr dismissView]; 
                }
                    
                if (request.endAction == @selector(resetPasswordEnd:)) {
                    GKBMainController *mainCtr = [GKBMainController mainCtr];
                    [LoginController1 setAutoLogin:NO];
                    [mainCtr dismissView];
                }
                NSString *timeout = NSLocalizedString(@"time out", nil);
                [iToast showTip:timeout gravity:iToastGravityCenter];
                [parser release];
                [Document release];
                return;
            }
        }
       
        [request.endTarget performSelector:request.endAction withObject:jsonData];
        
        
    }

    [parser release];
    [Document release];
    
}
- (void)requestWrong:(MyFormDataRequest*)request
{
    NSError *error;
    error = [request error];    
    //[common SimpleAlertWithTitle:nil msg:@"网络状态错误"];
   
    [self removeConnectTip];
//    [iToast showTip:self.errorTip gravity:iToastGravityBottom];
    if (request.errorTip) {//设置提示
        if ([request.errorTip isEqualToString:@"No Prompt"]) {
            NSLog(@"no prompt");
            [WebServices setShowConnectting:NO];//关闭提示
        }
        else
        {
            [iToast showTip: request.errorTip gravity:iToastGravityBottom];
        }
    }
    else//未设置提示
    {
    }
//    else if (![self.errorTip isEqualToString:@"No Prompt"]) {
//        [iToast showTip: NSLocalizedString(@"connectFail", nil) gravity:iToastGravityBottom];
//    }   
    [self removeQueueIndex:request.index];
}
- (void)requestFinished:(MyFormDataRequest *)request
{
    [self removeConnectTip];
    [self removeRequestDicIndex:request.index];
    
    NSString *responseString;
    responseString = [request responseString];
    //    NSLog(@"requestDone:%@",responseString);
    
    NSError *error;
    
    GDataXMLDocument *Document = [[GDataXMLDocument alloc]initWithXMLString:responseString options:0 error:&error];
    if (Document == nil) {
        NSString *errorType = [OperationTip errorType:ErrorTypeServerDataFail];
        [iToast showTip:errorType gravity:iToastGravityBottom];
        return;
    }
    GDataXMLElement *rootNode = [Document rootElement];    
    
    NSString *loginReturn = [xmlMore GetNodeString:rootNode node:@"/soapenv:Envelope"];      
    SBJsonParser *parser=[[SBJsonParser alloc] init];     
    NSArray *arrayData=[parser objectWithString:loginReturn];
    
    NSDictionary *jsonData=[arrayData objectAtIndex:0];
    if (request.endTarget && request.endAction) {
        NSLog(@"net end");        
        
        if (![WebServices showConnectting]) {
            NSNumber *result = [jsonData objectForKey:@"result"];
            if (result.integerValue == 2) {//session超时
                GKBMainController *mainCtr = [GKBMainController mainCtr];
                if (mainCtr) {
                    [LoginController1 setAutoLogin:NO];
                    [mainCtr dismissView];
                }
                
                if (request.endAction == @selector(resetPasswordEnd:)) {
                    GKBMainController *mainCtr = [GKBMainController mainCtr];
                    [LoginController1 setAutoLogin:NO];
                    [mainCtr dismissView];
                }
                NSString *timeout = NSLocalizedString(@"time out", nil);
                [iToast showTip:timeout gravity:iToastGravityCenter];
                [parser release];
                [Document release];
                return;
            }
        }
        
        [request.endTarget performSelector:request.endAction withObject:jsonData];
        
    }
    
    [parser release];
    [Document release];
}
- (void)requestFailed:(MyFormDataRequest *)request
{
    [self removeConnectTip];
    if (request.errorTip) {//设置提示
        if ([request.errorTip isEqualToString:@"No Prompt"]) {
            NSLog(@"no prompt");
            [WebServices setShowConnectting:NO];//关闭提示
        }
        else
        {
            [iToast showTip: request.errorTip gravity:iToastGravityBottom];
        }
    }
    else//未设置提示
    {
    }
    
    [request.endTarget performSelector:request.endAction withObject:nil];
    [self removeRequestDicIndex:request.index];
}
+ (NSString *)bodyWithOrder:(NSString *)order param:(NSString *)json
{
    NSString *fomat = @"<soapenv:Envelope xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\" xmlns:mob=\"http://moblieclient.gkb.com\"><soapenv:Header/><soapenv:Body><mob:%@ soapenv:encodingStyle=\"http://schemas.xmlsoap.org/soap/encoding/\"><configParamStr xsi:type=\"xsd:string\">%@</configParamStr></mob:%@></soapenv:Body></soapenv:Envelope>";
    NSString *body = [NSString stringWithFormat:fomat, order, json, order];
    return body;
}
+ (void)requestSet:(ASIFormDataRequest *)request withBody:(NSString *)body
{
    [request setRequestMethod:@"POST"];
    [request addRequestHeader:@"SOAPAction" value:@""];
    //[request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"];
    [request addRequestHeader:@"Content-Type" value:@"text/xml; charset=utf-8"];    
    NSMutableData *bodyData = [NSMutableData dataWithBytes:[body UTF8String] length:[body length]];
    [request addRequestHeader:@"Content-Length" value:[NSString stringWithFormat:@"%u", [bodyData length]]];
    NSLog(@"__body:%@", body);
    [request setPostBody:bodyData];
}
+ (MyFormDataRequest *)requestOrder:(NSString *)order param:(NSString *)json
{
    MyFormDataRequest *request = [MyFormDataRequest requestWithURL:[WebServices url]];
    [request setTimeOutSeconds:30];
    [request setShouldAttemptPersistentConnection:NO];//避免重复请求
    NSString *body = [WebServices bodyWithOrder:order param:json];
    [WebServices requestSet:request withBody:body];
    return request;
}

+ (MyFormDataRequest *)requestStartOrder:(NSString *)order body:(NSString *)json target:(id)target action:(SEL)action errorTip:(NSString *)errorTip
{
    WebServices *service = [WebServices webService];

    MyFormDataRequest *request = [WebServices requestOrder:order param:json];
    request.index = service.queueIndex;
    [request setDelegate:service];
    [service saveRequestDic:request];
    [request setEndTarget:target endAction:action errorTip:errorTip];
    //[service startOperation:request];
    [service startRequest:request];
    
    return request;

}
- (void)addConnectTip
{

    UIView *tipView = [[UIView alloc]init];
                        
    [tipView setFrame:CGRectMake(0, 0, DEVICE_WIDTH,DEVICE_HEIGHT )];
   // [tipView setBackgroundColor:[UIColor blackColor]];
    
    [tipView setTag:kConnectTipView];
    if ([UIDevice currentDevice].systemVersion.floatValue >= 8.0) {
//        [tipView setCenter:CGPointMake(DEVICE_WIDTH/2, DEVICE_HEIGHT/2)];
    }
    else
    {
        tipView.transform = CGAffineTransformMakeRotation((180 *M_PI)/360);
        [tipView setCenter:CGPointMake(DEVICE_WIDTH/2, DEVICE_HEIGHT/2)];
    }
    
    UIView *backView = [[UIView alloc]init];    
    [backView setFrame:CGRectMake(0, 0, DEVICE_WIDTH, DEVICE_HEIGHT)];
    [backView setAlpha:0.5];
    [backView setBackgroundColor:[UIColor blackColor]];
    [tipView addSubview:backView];
    [backView release];
    
    CGFloat indicatorW = 37.0f;
    
    CGFloat startX = (DEVICE_WIDTH/2 - indicatorW*2 );//170
    
    UIActivityIndicatorView *indicator = [[UIActivityIndicatorView alloc]initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge];
    [indicator setFrame:CGRectMake(DEVICE_WIDTH*0.5f, DEVICE_HEIGHT*.05f, 37, 37)];
    [indicator setCenter:CGPointMake(DEVICE_WIDTH*0.5f, kScreenHeight*0.5f-20)];
    [indicator startAnimating];
    [tipView addSubview:indicator];
    [indicator release];
    
    UILabel *text = [[UILabel alloc]initWithFrame:CGRectMake(startX + indicatorW, 130, 200, 37)];
    [text setBackgroundColor:[UIColor clearColor]];
    [text setTextColor:[UIColor whiteColor]];
   // [text setText:NSLocalizedString(@"Loading...", nil)];
    [tipView addSubview:text];
    [text release];
  
    
    [[UIApplication sharedApplication].keyWindow addSubview:tipView];
    [tipView release];  
}

- (void)removeConnectTip
{
    UIView *view = [[UIApplication sharedApplication].keyWindow viewWithTag:kConnectTipView];
    [view removeFromSuperview];
}
//- (void)requestStarted:(MyFormDataRequest *)request
//{
//    NSString *fun = NSStringFromSelector(request.endAction);
//    NSLog(@"%@", fun);
//}
+ (void)removeRequest:(MyFormDataRequest *)request
{
    [request clearDelegatesAndCancel];
    
    WebServices *service = [WebServices webService];
    [service removeRequestDicIndex:request.index];
}


+ (void)requestSynStartOrder:(NSString *)order body:(NSString *)json result:(void(^)(NSDictionary *dic))result
{
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        
        MyFormDataRequest *request = [WebServices requestOrder:order param:json];
        //[service startOperation:request];
        [request startSynchronous];
        
        NSString *responseString;
        responseString = [request responseString];
        //    NSLog(@"requestDone:%@",responseString);
        
        NSError *error;
        
        GDataXMLDocument *Document = [[GDataXMLDocument alloc]initWithXMLString:responseString options:0 error:&error];
        
        GDataXMLElement *rootNode = [Document rootElement];
        
        NSString *loginReturn = [xmlMore GetNodeString:rootNode node:@"/soapenv:Envelope"];
        SBJsonParser *parser=[[SBJsonParser alloc] init];
        NSArray *arrayData=[parser objectWithString:loginReturn];
        
        NSDictionary *jsonData=[arrayData objectAtIndex:0];
        
        [parser release];
        [Document release];
        
        dispatch_async(dispatch_get_main_queue(), ^{
            if (result) {
                result(jsonData);
            }
        });
    });
    
}

@end
